#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

class SafeFile
{
public:
    //在构造函数中初始化资源
    SafeFile(FILE *fp)
    : _fp(fp)
    {
        cout << "SafeFile(FILE *)" << endl;
        if(nullptr == _fp)
        {
            cout << "nullptr ==_fp" << endl;
        }
    }

    //提供若干访问资源的方法
    void write(const string &msg)
    {
        fwrite(msg.c_str(), 1, msg.size(), _fp);
    }

    //在析构函数中释放资源
    ~SafeFile()
    {
        cout << "~SafeFile()" << endl;
        if(_fp)
        {
            fclose(_fp);
        }
    }
private:
    FILE *_fp;
};

void test()
{
    SafeFile sf(fopen("wd.txt", "a+"));//sf是栈对象
    sf.write("hello,world\n");
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

